import JSZip from 'jszip'
import styles from './scss/editBox.module.scss'
import { createResolvablePromise } from '@/utils/common'
import GifCanvas from './gifCanvas'
import { getScaleCanvasSize } from '@/lib/gifEdit/common'

interface Props {
  show: boolean
  images: string[]
  width: number
  height: number
  duration: number
  onReupload: () => void
}
async function imageUrlToBlob(url: string) {
  const [p, resolve] = createResolvablePromise<Blob>()
  const image = new Image()
  image.src = url
  await image.decode()
  const canvas = document.createElement('canvas')
  canvas.width = image.width
  canvas.height = image.height
  const ctx = canvas.getContext('2d')
  ctx.drawImage(image, 0, 0)
  canvas.toBlob((b) => {
    resolve(b)
  }, 'image/png')
  return p
}
export function EditBox(props: Props) {
  const canvasSize = getScaleCanvasSize(props.width, props.height, 120)
  return (
    <div
      className={`${styles['edit-box']}${
        !props.show ? ` ${styles['edit-box-hide']}` : ''
      }`}>
      <div className={styles.content}>
        <div className={styles.gifCanvas}>
          <GifCanvas
            width={props.width}
            height={props.height}
            images={props.images}
            duration={props.duration}
          />
        </div>
        <div className={styles['image-table']}>
          {props.images &&
            props.images.map((item, _) => {
              return (
                <div
                  className={styles['edit-image-box-item']}
                  key={item}
                  style={{
                    width: canvasSize.width,
                    height: canvasSize.height,
                  }}>
                  <img src={item} alt="" />
                </div>
              )
            })}
        </div>
      </div>

      <div className={styles['image-edit-btns']}>
        <button
          className={styles['btn']}
          onClick={async () => {
            const zip = new JSZip()
            const img = zip.folder('images')
            await Promise.all(
              props.images.map(async (item, index) => {
                const blob = await imageUrlToBlob(item)
                img.file(`${index}.png`, blob, { base64: true })
              })
            )
            zip.generateAsync({ type: 'blob' }).then((content) => {
              const a = document.createElement('a')
              a.href = URL.createObjectURL(content)
              a.download = 'images.zip'
              a.click()
            })
          }}>
          导出
        </button>
        <button className={styles['btn']} onClick={props.onReupload}>
          重新上传
        </button>
        {/* <button className="btn">导出</button> */}
      </div>
    </div>
  )
}
